package cn.com.http.httpmessage;

import java.io.UnsupportedEncodingException;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import cn.com.charset.Charsets;
import cn.com.logger.LoggerManager;

public class HttpContent {
	private static final byte[] EMPTY_ARRAY = new byte[0];

	private Logger log = LoggerManager.getLogger(HttpContent.class);

	private byte[] content = EMPTY_ARRAY;

	private String charset = Charsets.HTTP;

	public final void clear() {
		content = EMPTY_ARRAY;
	}

	public final String getCharset() {
		return charset;
	}

	public final void setCharset(String charset) {
		if (charset == null)
			throw new NullPointerException();
		this.charset = charset;
	}

	public int length() {
		return content.length;
	}

	public byte[] toByteArray() {
		return content;
	}

	public String toString() {
		try {
			return new String(content, charset);
		} catch (UnsupportedEncodingException e) {
			if (log.isEnabledFor(Level.ERROR))
				log.error(e.getMessage(), e);
		}
		return new String(content);
	}

	public void setContent(byte[] content) {
		if (content == null)
			throw new NullPointerException();
		this.content = content;
	}

	public void set(String content, String charset)
			throws UnsupportedEncodingException {
		setCharset(charset);
		setContent(content.getBytes(charset));
	}
}
